
import json
import urllib3
import xlrd
import math
import datetime
import time
from  decimal import Decimal
http = urllib3.PoolManager(num_pools=5, maxsize=10)

# ---Global---
investor_id = 'ZJH'
#server_url = "http://172.24.7.76:8081"
server_url = "stock-portfolio.jr.jd.com"
create_url = server_url + "/portfolio/create"
update_url = server_url + "/portfolio/update"
trade_url = server_url + "/trade"

INIT_CAPITAL = 1000000


def Auth(_investor_id):
    from datetime import datetime
    import hashlib

    # 待加密信息
    mark = 'portfolio'
    investor_id = str(_investor_id)
    dt = datetime.now().strftime("%Y-%m-%d %H:%M:%S")

    key = investor_id + '_' + dt + '_' + mark
    # 创建md5对象
    md5_hash = hashlib.md5()
    md5_hash.update(key.encode(encoding='utf-8'))

    # Tips
    # 此处必须声明encode
    # 若写法为hl.update(str) 报错为： Unicode-objects must be encoded before hashing

    # print('MD5加密前为 ：' + key)
    # print('MD5加密后为 ：' + md5_hash.hexdigest())
    result = {'investor_id' : investor_id, 'date' : dt, 'md5' : md5_hash.hexdigest()}
    return result


def CreatePortfolio(portfolioName, info="NA"):
    #
    url = create_url
    body = {}
    body["name"] = portfolioName
    body["info"] = info
    body["base_code"] = "000300.SH"
    body["init_amount"] = INIT_CAPITAL
    body["commission"] = 0
    body["status"] = 0
    body["group_id"] = "test_group"
    body['auth'] = Auth(investor_id)
    body['investor_id'] = investor_id

    #
    b = json.dumps(body)
    print(b)
    response = http.request('POST', url, body=json.dumps(body), timeout=1)
    print(url, response.status, response.data.decode('utf8'))
    portfolio_id = json.loads(response.data.decode('utf8'))['code_msg']['portfolio_id']
    pass


def UpdatePortfolio(portfolio_id,
                    updatePortfolioName=None,
                    updateInfo=None,
                    updateBenchmarkSymbol=None):

    body = {}
    body["portfolio_id"] = portfolio_id

    if updatePortfolioName:
        body["name"] = updatePortfolioName

    if updateInfo:
        body["info"] = updateInfo

    if updateBenchmarkSymbol:
        body["base_code"] = updateBenchmarkSymbol

    # body["commission"] = 0
    # body['status'] = 0

    # portfolio_id = json.loads(response.data.decode('utf8'))['code_msg']['portfolio_id']
    url = update_url
    body['portfolio_id'] = portfolio_id
    body['auth'] = Auth(investor_id)
    response = http.request('POST', url, body = json.dumps(body), timeout=1)
    print(url, response.status, response.data.decode('utf8'))


def Update(portfolio_id, updateField, updateValue):
    body = {}
    body["portfolio_id"] = portfolio_id
    body[updateField] = updateValue
    url = update_url
    body['portfolio_id'] = portfolio_id
    body['auth'] = Auth(investor_id)
    response = http.request('POST', url, body=json.dumps(body), timeout=1)
    print(url, response.status, response.data.decode('utf8'))

# symbol : 000001.SZ
# side: buy / sell
# qty: 100 / 500 / 1000
# price: 9.5
# tradeDatetime: "2018-09-14 22:41:50"
def AddTrade(portfolio_id, symbol, side, qty, price, tradeDateTime):

    body = {}

    body["portfolio_id"] = portfolio_id
    body["code"] = symbol
    body['volume'] = int(qty / 100.0) * 100
    body['price'] = price
    body['trade_time'] = ToDateTimeString(tradeDateTime)
    body['direction'] = side
    body['auth'] = Auth(investor_id)

    url = trade_url
    response = http.request('POST', url, body=json.dumps(body), timeout=5)
    print(url, response.status, response.data.decode('utf8'))


def AddTag(portfolio_id, tag, id=1):
    url = server_url + "/lable/add"
    body = {"portfolio_id": portfolio_id, 'lable': [{'id': id, 'info': tag}]}
    body['auth'] = Auth(investor_id)

    #print(body)
    response = http.request('POST', url, body=json.dumps(body), timeout=1)
    print(url, response.status, response.data.decode('utf8'))



def UpdateTag(portfolio_id, tag, id=1):
    lable_update_url = server_url + "/lable/update"
    lable_update_body = {"portfolio_id": portfolio_id, 'lable': [{'id': id, 'info': tag}]}


def QryPositions(portfolio_id):
    #http: // stock - portfolio.jr.jd.com / search / portfolio?portfolio_id = 2

    url = server_url + "/search/portfolio"
    body = {}
    body['portfolio_id'] = portfolio_id

    response = http.request('GET', url, fields=body, timeout=1)
    print(url, response.status, response.data.decode('utf8'))

    s = response.data.decode('utf8')
    document = eval(s)
    return document["positon_list"]



def ToDateTimeString(date):
    s = date.strftime('%Y-%m-%d %H:%M:%S')
    return s


def ReadExcelFile(excelPathfilename, sheetName = "Sheet1"):

    # ---Load Text File---
    book = xlrd.open_workbook(excelPathfilename)
    sheet = book.sheet_by_name(sheetName)

    nrows = sheet.nrows
    ncols = sheet.ncols
    i = 0;
    headerIndexByName = {}
    table = []
    for i in range(0, nrows):
        row_data = sheet.row_values(i)
        content = row_data
        if content[0] == "":
            continue

        # Process Headers
        if i == 0:
            headerCount = 0
            for header in content:
                headerIndexByName[header] = headerCount
                headerCount = headerCount + 1
            continue
        # Process Header Done

        #Process Contents
        entry = []
        for data in content:
            #data = data.strip("\n")
            entry.append(data)
        table.append(entry)

    return headerIndexByName, table


def ReadCSVFile(pathFilename,spliter = ","):
    file = open(pathFilename, 'r')
    i = 0
    headerIndexByName = {}
    table = []
    while True:
        s = file.readline()
        i = i+1
        if s == '':
            break

        content = s.split(spliter)
        #Process Headers
        if i == 1:
            headerCount = 0
            for header in content:
                header = header.strip(" ")
                header = header.strip("\n")
                headerIndexByName[header] = headerCount
                headerCount = headerCount + 1
            continue

        #Process Contents
        entry = []
        for data in content:
            data = data.strip("\n")
            entry.append(data)
        table.append(entry)

    return headerIndexByName,table


def RebalancePortfolio(excelPathfileName, portfolioId):
    header, data = ReadExcelFile(excelPathfileName)

    positionsBySymbol = {}
    positions = QryPositions(portfolioId)
    for position in positions:
        positionsBySymbol[position["code"]] = position

    sellTrades = []
    buyTrades = []

    for d in data:

        symbol = d[header["Symbol"]]
        target = d[header["Qty"]]
        current = 0
        position = positionsBySymbol.get(symbol)
        if position:
            current = position["volume"]

        #
        qty = target - current

        #
        if qty > 0:
            side = "buy"
        elif qty < 0:
            side = "sell"
        else:
            continue

        price = float(d[header["Price"]])
        tradeDate = str(int(d[header["Date"]]))  # wind "20180927"
        tradeTime = d[header["Time"]]  # wind "11:29:59"
        strDateTime = tradeDate + " " + tradeTime
        tradeDateTime = datetime.datetime.strptime(strDateTime, "%Y%m%d %H:%M:%S")

        doc = {"Symbol":symbol, "Side":side, "Qty": qty, "Price": price, "TradeDateTime": tradeDateTime}
        if side == "buy":
            buyTrades.append(doc)
        elif side == "sell":
            sellTrades.append(doc)

        print(symbol, side, "Qty", qty, "Price",price)

    # ---Sell First then Buy
    totalTrades = sellTrades + buyTrades
    for trade in totalTrades:
        print(trade)
        #continue
        AddTrade(portfolio_id=portfolioId,
                 symbol=trade["Symbol"],
                 side=trade["Side"],
                 qty=math.fabs(trade["Qty"]),
                 price=trade["Price"],
                 tradeDateTime=trade["TradeDateTime"])
        print("")
    k = 0


#####################################################################3
# ---开始---

# 建立组合
# CreatePortfolio("BigPlayer")
# CreatePortfolio("HolderRiskOn")
#CreatePortfolio("价值洼地策略","小白策略之价值洼地策略从市净率，市盈率，净利润增长率以及分红率四个维度，筛选出处于价值洼地的股票。")
pass


# 存储组合名和ID的对照表
portdolioIDTable = {}
portdolioIDTable["次新股策略"] = 14
portdolioIDTable["乔尔选股策略"] = 18
portdolioIDTable["价值洼地策略"] = 21

pass


#AddTag(4, "中长期")
#AddTag(5, "中长期")
pass


# Update(4, "name", "国家队动向")
# Update(4, "info", "跟踪国家队基金持股，发现价值投资新动向")

#Update(5, "name", "大股东增持")
#Update(5, "info", "发现大股东增持的秘密，股票市场常青藤策略")

# Use Excel To Trade
#RebalancePortfolio("D:\Data\PortfolioManagement\大股东增持.xlsx", portdolioIDTable["HolderRiskOn"])
#RebalancePortfolio("D:\Data\PortfolioManagement\BigPlayer.xlsx", portdolioIDTable["BigPlayer"])
#RebalancePortfolio("D:\Data\PortfolioManagement\BigPlayer_2018-11-1_Buy.xlsx", portdolioIDTable["BigPlayer"])
#RebalancePortfolio("D:\PortfolioManagement\Mr.Bai_10_20181115.xlsx", portdolioIDTable["次新股策略"])
#RebalancePortfolio("D:\PortfolioManagement\Mr.Bai_3_20181130.xlsx", portdolioIDTable["价值洼地策略"])